<style scoped>
    body{background:#000;}
    .header,.footer{display:none;}
    #body_content{overflow:hidden;margin-left: 0px!important;padding-top: 0px;}
    .side{display: none;}
    .content{
        padding:0px;
        color:#fff;
        width:calc(100%);
        height:calc(100%);
        background:#000;
    }
    .console-header{
        width:100%;
        height:40px;
        display: flex;
        flex-direction: row;
        align-items: center;
        background:#5a5454;
    }
    .console-header .home{
        width:60px;
        height:40px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        cursor:pointer;
        margin-right:50px;
    }
    .console-header .item{
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 10px;
    }
    .console-header .item .inp1{
        width:250px;
    }
    .el-input__inner {
        background-color: #5a5454;
        color: #dedfe2;
        height: 30px;
        line-height: 30px;
        border: none;
    }
    .el-input__icon {
        line-height: 30px;
    }
    .console-header-list .empty{
        padding:15px 10px;
        font-size:14px;
    }
    .console-header-list .child{
        line-height:30px;
        cursor: pointer;
        padding-left:10px;
    }
    .console-header-list .child:hover{
        color:#000;
        background-color: #F5F7FA;
    }
    .console-header-list .select-all{
        margin:10px 0 0 10px;
    }
    .console-header .line{
        height:20px;
        width:1px;
        background:#ccc;
        margin:0 25px;
    }
    .comsole-consten{
        width:calc(100%);
        height:calc(100% - 80px);
        position: relative;
        overflow:hidden;
    }
    .comsole-consten .navs{
        display: flex;
        flex-direction: row;
        align-items: center;
        height:30px;
        font-size:12px;
        background:#3a3333;
        color:#aaa;
        padding:0 10px;
        width:calc(100%);
    }
    .comsole-consten .navs .item{
        display: flex;
        flex-direction: row;
        align-items: center;
        padding:0 10px;
        height:100%;
        cursor:pointer;
    }
    .comsole-consten .navs .item span{
        display: block;
        max-width:150px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right:5px;
    }
    .comsole-consten .navs .active{
        color:#fff;
        border-bottom:solid 2px #409eff;
    }
    .comsole-consten .navs .item i{
        cursor:pointer;
        font-size:16px;
    }
    .xterm-list{
        width:calc(100%);
        height:calc(100%);
        position: relative;
    }
    .xterm-list .xterm-item{
        left:10px;
        top:10px;
        position: absolute;
        width:calc(100% - 10px);
        height:calc(100% - 50px);
    }
    .console-side .el-menu-item-group__title{
        padding:0;
    }
    .console-side .el-submenu__title{
        font-size:12px;
        height:35px;
        line-height:35px;
    }
    .console-side .el-submenu .el-menu-item{
        font-size:12px;
        height: 30px;
        line-height: 30px;
        padding-right:10px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .console-footer{
        height:40px;
        background:#5a5454;
        padding-left:100px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }
    .console-footer input{
        width:800px;
        height:30px;
        padding-left:10px;
        font-size:14px;
        letter-spacing:1px;
        border:none;
    }
</style>
<div class="content" id="team" v-cloak>
    <div class="console-header">
        <div class="home" @click="goHome"><i class="el-icon-s-home fs-22"></i></div>
        <div class="line"></div>
        <div class="item">
            <!-- <span>通过团队筛选：</span> -->
            <el-select v-model="team_name" class="w-200" placeholder="请选择团队">
                <el-option v-for="(val, name, index) in assets" :key="name" :label="name" :value="name" ></el-option>
            </el-select>
        </div>
        <div class="item">
            <el-popover placement="bottom-start" width="300" trigger="hover">
                <div class="console-header-list">
                    <div v-if="assetslist.length?true:false">
                        <div class="child" v-for="item in assetslist" :key="item.code" @click="addXtermForAssets(item)">{{item.name}}</div>
                        <el-button class="select-all" type="primary" size="small" @click="addAllToXterm(1)">全部选择</el-button>
                    </div>
                    <div v-if="!assetslist.length?true:false" class="empty">请先选择团队信息。</div>
                </div>
                <div class="select-btn" slot="reference">请选择需要打开的资产</div>
            </el-popover>
        </div>
        <div class="line"></div>
        <div class="item">
            <!-- <span>通过应用筛选：</span> -->
            <el-select v-model="app_name" class="w-200" placeholder="请选择应用">
                <el-option v-for="(val, name, index) in application" :key="name" :label="name" :value="name"></el-option>
            </el-select>
        </div>
        <div class="item">
            <el-popover placement="bottom-start" width="300" trigger="hover">
                <div class="console-header-list">
                    <div v-if="applicationlist.length?true:false">
                        <div class="child" v-for="item in applicationlist" :key="item.code" @click="addXtermForAssets(item)">
                            {{item.name}}</div>
                        <el-button class="select-all" type="primary" size="small" @click="addAllToXterm(2)">全部选择</el-button>
                    </div>
                    <div v-if="!applicationlist.length?true:false" class="empty">请先选择应用信息。</div>
                </div>
                <div class="select-btn" slot="reference">请选择需要打开的资产</div>
            </el-popover>
        </div>
        <div class="line"></div>
    </div>
    <div class="comsole-consten">
        <div class="navs">
            <div 
                v-for="(item,index) in xtermList" 
                :key="index" 
                class="item"
                :style="{'max-width':(1/xtermList.length)*100+'%'}"
                @click="selectTab(item)"
                :data-i="navIndex+'--'+item.xtermId"
                :title="item.name+'-'+item.outer_ip+'-'+item.lan_ip"
                :class="{active:navIndex==item.xtermId?true:false}">
                <span>{{item.name+'-'+item.outer_ip}}</span>
                <i @click.stop="closeXtermForAssets(index,item)" class="el-icon-close"></i>
            </div>
        </div>
        <div class="xterm-list">
            <div 
                class="xterm-item"
                :style="{'z-index':navIndex==item.xtermId?20:1}"
                v-for="(item,index) in xtermList" 
                :key="item.xtermId" 
                :id="'console_terminal_'+item.xtermId"></div>
        </div>
    </div>
    <div class="console-footer">
        <span>全局运行指令：</span>
        <input type="text" v-model="instructions" @keyup="onKeyUp" @keyup.enter="onEnter" placeholder="请输入">
    </div>
</div>
<script>
    const xtermRunList = [];
    let xtermId = -1;
    const key_storage = util.getStorage('local', 'console_key_history');
    const keyHistory = key_storage ? JSON.parse(key_storage).splice(-20) : [];
    let hisBegin = keyHistory.length;
    new Vue({
        el: '#team',
        data: function () {
            return {
                assets:{},
                xtermList:[],
                navIndex:0,
                assetslist: [],
                assets_name: '',
                team_name:'',
                instructions:'',
                app_name: '',
                application:{},
                applicationlist:[],
            }
        },
        watch:{
            'team_name'(newVal,oldVal){
                if(newVal !== oldVal){
                    this.assetslist = this.assets[newVal];
                }
            },
            'app_name'(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.applicationlist = this.application[newVal];
                }
            },
        },
        mounted() {
            $('#body_content').css('height',$(window).height() +'px');
            this.assetsList();
            this.applicationList();
            this.socket = util.socket();
            this.fullscreen();
        },
        methods: {
            assetsList(){
                util.ajax({
                    type:'get',
                    url:`${config.baseApi}api/v1/assets/all`,
                    success:data=>{
                        const datas = data.data || [];
                        const assets = {};
                        const xtermList = [];
                        let ids = util.getQueryString('ids');
                        ids = ids ? ids.split(',') : [];
                        let i = 0;
                        datas.forEach((item,index) => {
                            if(ids.includes(item._id)){
                                item.xtermId = i;
                                i++;
                                xtermList.push(item);
                            }
                            if(!assets[item.teamlist[0].name]){
                                assets[item.teamlist[0].name] = [ item ];
                            } else {
                                assets[item.teamlist[0].name].push(item);
                            }
                        })
                        this.xtermList = xtermList;
                        this.assets = assets;
                        xtermId = this.xtermList.length-1;
                        setTimeout(()=>{
                            this.xtermList.forEach((item,index)=>{
                                this.showConsole(index, item)
                            })
                        },200)
                    }
                })
            },
            applicationList() {
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/application/all`,
                    success: data => {
                        const datas = data.data || [];
                        const application = {};
                        const xtermList = [];
                        datas.forEach((item, index) => {
                            if (!application[item.name]) {
                                application[item.name] = item.assets_list;
                            }
                        })
                        this.application = application;
                    }
                })
            },
            selectTab(item){
                this.navIndex = item.xtermId;
            },
            addAllToXterm(type){
                const assetslist = type === 1 ? this.assetslist : this.applicationlist;
                assetslist.forEach( item => this.addXtermForAssets(item) )
            },
            addXtermForAssets(item){
                item = JSON.parse(JSON.stringify(item))
                xtermId++
                this.navIndex = xtermId;
                item.xtermId = xtermId;
                this.xtermList.push(item);
                setTimeout((xtermId)=>{ this.showConsole(xtermId, item); }, 200, xtermId);
            },
            closeXtermForAssets(index,item){
                const xterm = xtermRunList[index];
                xterm.destroy();
                this.socket.emit('console_close_'+ item.xtermId)
                this.xtermList.splice(index,1);
                xtermRunList.splice(index, 1);
                if(item.xtermId !== this.navIndex) return;

                if(this.xtermList[index]){
                    this.navIndex = this.xtermList[index].xtermId;
                }else if(this.xtermList[index-1]){
                    this.navIndex = this.xtermList[index-1].xtermId;
                }else{
                    this.navIndex = -1
                }
            },
            xtrem(){
                var term = new Terminal();
                term.open(document.getElementById('console_terminal_0'));
                term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
            },
            showConsole(index,assetsItem){
                const xteam = util.xteam({
                    index,
                    socket: this.socket,
                    assetsItem,
                })
                xtermRunList.push(xteam);
            },
            goHome(){
                location.href="/"
            },
            onEnter(){
                const xtermList = this.xtermList;
                if(!xtermList || !xtermList.length) {
                    popup.alert({title:'请登录中的资产!'});
                    return;
                }
                
                xtermList.forEach(item => {
                    this.socket.emit('console_data_'+ item.xtermId, this.instructions + '\n')
                })
                keyHistory.push(this.instructions);
                hisBegin = keyHistory.length;
                util.setStorage('local','console_key_history',JSON.stringify(keyHistory));
                this.instructions = '';
            },
            onKeyUp(e){
                if(e.code === 'ArrowUp'){
                    if (hisBegin > 0) {
                        hisBegin--
                        this.instructions = keyHistory[hisBegin];
                    }
                }else if(e.code === 'ArrowDown'){
                    if (hisBegin < keyHistory.length-1) {
                        hisBegin++
                        this.instructions = keyHistory[hisBegin];
                    }
                }
            },
            fullscreen(){
                const _this = this;
                $(document).keyup(function (event) {
                    console.log(event.keyCode)
                    if (event.keyCode === 112) {
                        if(xtermRunList && xtermRunList[_this.navIndex]){
                            xtermRunList[_this.navIndex].toggleFullScreen();
                        }
                    }
                });
            },
        }
    })
</script>